package com.ybb.vue.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ybb.vue.common.Result;
import com.ybb.vue.common.util.ExcelUtils;
import com.ybb.vue.common.util.OperationRecordsUtils;
import com.ybb.vue.common.util.RandCreateHealStatusUtils;
import com.ybb.vue.common.util.StringUtil;
import com.ybb.vue.domain.vo.EpmResidentImprotVo;
import com.ybb.vue.domain.dto.EpmResidentSaveDto;
import com.ybb.vue.domain.dto.EpmResidentUpdateDto;
import com.ybb.vue.entity.EpmResident;
import com.ybb.vue.mapper.EpmResidentMapper;
import com.ybb.vue.service.EpmResidentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author apple
* @description 针对表【resident(居民表)】的数据库操作Service实现
* @createDate 2023-03-02 13:42:34
*/
@Service
public class EpmResidentServiceImpl extends ServiceImpl<EpmResidentMapper, EpmResident>
implements EpmResidentService {

    @Autowired
    private EpmResidentMapper residentMapper;

    @Override
    public Result saveResident(EpmResidentSaveDto residentSaveDto) {
        EpmResident resident = residentMapper.selectOne(new QueryWrapper<EpmResident>().eq("id_card", residentSaveDto.getIdCard()));
        if (resident != null) {
            return Result.error("-1","该身份证已存在，不能重复添加居民信息！");
        }
        EpmResident residentInsert = new EpmResident();
        BeanUtils.copyProperties(residentSaveDto, residentInsert);
        // 默认绿码
        residentInsert.setHealthStatus("0");
        this.save(residentInsert);

        // 操作记录
        String content = "操作了居民表，【新增】了1条记录，记录id为：" + residentSaveDto.getId();
        OperationRecordsUtils.createOperationRecords(content);
        return Result.success();
    }

    @Override
    public Result updateResident(EpmResidentUpdateDto residentUpdateDto) {
        String phoneNumber = residentUpdateDto.getPhoneNumber();
        String idCard = residentUpdateDto.getIdCard();
        StringBuffer phoneNumberStringBuffer = new StringBuffer();
        StringBuffer idCardStringBuffer = new StringBuffer();

        EpmResident residentData = residentMapper.selectOne(new QueryWrapper<EpmResident>().eq("id", residentUpdateDto.getId()));

        // 若不带有*号
        if (!phoneNumber.contains("*")) {
            if (!phoneNumber.matches("^[\\d\\*]{7,12}$")) {
                return Result.error("-1", "手机号格式有误！");
            } else {
                phoneNumberStringBuffer.append(phoneNumber);
            }
        }else{
            // 替换前三位和后三位
            phoneNumberStringBuffer.append(residentData.getPhoneNumber());
            phoneNumberStringBuffer.replace(0, 3, phoneNumber.substring(0, 3));
            phoneNumberStringBuffer.replace(8, 11, phoneNumber.substring(8, 11));
        }

        if (!idCard.contains("*")) {
            if (!idCard.matches("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$")) {
                return Result.error("-1", "身份证号格式有误！");
            } else {
                idCardStringBuffer.append(idCard);
            }
        } else {
            // 替换前三位和后三位
            idCardStringBuffer.append(residentData.getIdCard());
            idCardStringBuffer.replace(0, 3, idCard.substring(0, 3));
            idCardStringBuffer.replace(15, 18, idCard.substring(15, 18));
        }

        residentUpdateDto.setPhoneNumber(new String(phoneNumberStringBuffer));
        residentUpdateDto.setIdCard(new String(idCardStringBuffer));

        EpmResident residentInsert = new EpmResident();
        BeanUtils.copyProperties(residentUpdateDto, residentInsert);

        // 操作记录
        String content = "操作了居民表，【修改】了1条记录，记录id为：" + residentUpdateDto.getId();
        OperationRecordsUtils.createOperationRecords(content);
        return Result.success(this.updateById(residentInsert));
    }

    @Override
    @Transactional
    public Result importResident(MultipartFile file) throws Exception {
        List<EpmResidentImprotVo> residentImprotDtos = ExcelUtils.readMultipartFile(file, EpmResidentImprotVo.class);
        List<EpmResident> residentList = new ArrayList<>();
        for (EpmResidentImprotVo residentImprotDto : residentImprotDtos) {
            // 将导入的实体写入数据库
            EpmResident resident = new EpmResident();
            BeanUtils.copyProperties(residentImprotDto, resident);
            // 默认绿码
            resident.setHealthStatus("0");
            residentList.add(resident);
            // 有不符合格式的数据直接终止导入
            if (StringUtil.isNotEmpty(residentImprotDto.getRowTips())) {
                return Result.error("-1",residentImprotDto.getRowTips());
            }
        }
        // 批量写入数据库
        this.saveBatch(residentList);

        // 操作记录
        String content = "操作了居民表，【导入】了"+residentList.size()+"条记录";
        OperationRecordsUtils.createOperationRecords(content);
        return Result.success();
    }
}
